requireJS(['constant', 'site', 'handlebars', 'public', 'uploadImage', 'static/js/page/common/common.js'], function (Constant, site, Handlebars, Public, UploadImage, Common) {
    Constant.initHandlebars(Handlebars);
    Public.initApplyTerm();
    Public.initProductSearch();

    //全选功能
    $("input[name='ch_id_all']").on('click', function () {
        var _checked = $("input[name='ch_id']")
        if ($(this).prop('checked')) {
            _checked.prop('checked', true)
        }
        else {
            _checked.prop('checked', false)
        }
    })

    //保存订单信息
    /*var odata = "";
    var otask_id = "";
    var onode_id = "";*/
    var arr = [];
    var product_id;
    var order_id;
    var taskId;
    var node_type;
    var node_id;
    var last_node_id;
    var s_id;
    var approvalType;
    var repayment_way;
    var at_id;
    var applyHtml;

    var url = {
        queryTk: "manager/queryTk.do",
        queryOrder: 'manager/selectOrderPageList.do',
        queryAdminRoleByRole: "manager/queryAdminRoleByRoleId.do",
        roamTask: "manager/roamTask.do",
        delOrderAll: "manager/delOrderAll.do",
        selectPageLogList: "manager/selectPageLogList.do",
        getActivitiProccessImage: "manager/getActivitiProccessImage.do",
        selectLoanMethodList: "manager/selectLoanMethodList.do",

        /***************流程节点自定义表单***********************/
        queryEndNodeId: "manager/queryEndNodeId.do",
        selectLoanTypeList: "manager/selectLoanTypeList.do",
        selectApplyTermList: "manager/selectApplyTermList.do",
        selectOrderSourceList: "manager/selectOrderSourceList.do",
        selectRepanymentWayList: "manager/selectRepanymentWayList.do",
        queryLoanDefineByProductId: "manager/queryLoanDefineByProductId.do",
        queryNodeFromInfoAllByONid: "manager/queryNodeFromInfoAllByONid.do",
        saveNodefromInfos: "manager/saveNodefromInfos.do",
        backProcess: "manager/backProcess.do",
        ChoiceOfclient: "manager/ChoiceOfclient.do",
        entrustOrder: "manager/entrustOrder.do",
        selectAttachmentWait: "manager/selectAttachmentWait.do",

        /***************图片上传*****************/
        insertAttachment: "manager/insertAttachment.do",
        selectAttachmentType: "manager/selectAttachmentTypeproduct.do",
    }

    //用户登录取出缓存的用户登录信息
    var userMessage = {
        roleId: JSON.parse(localStorage.getItem('content')).admin.roleid,
        userId: JSON.parse(localStorage.getItem('content')).admin.id
    }

    //查询产品所需字段
    var frontData = {
        roleId: userMessage.roleId,
        pageNum: 1
    };

    //图片上传所需数组
    var attachImg = new Array();
    var attachimg = new Array();

    //渲染搜索框的贷款方式
    site.send({
        url: url.selectLoanMethodList,
        callback: function (data) {
            data = JSON.parse(data);
            if (data.type == '1') {
                var source = $("#loanMethod_list_tpl").html();
                var template = Handlebars.compile(source);
                var list = data
                var html = template(list)
                $('#loan_way').append(html);
            }
        }
    })

    function saveNodefromInfos() {
        var productInfos = new Array();
        //获取产品自定义真实数据信息
        var td = $(".productInfos").find('td[property_id]');
        $.each(td, function (i, e) {
            var productForm = $(e).find('[productForm]')
            if (productForm.attr('productForm') == 'text') {
                var obj = {
                    property_id: $(e).attr('property_id'),
                    name: $(e).attr('name'),
                    fixed_name: $(e).attr('name'),
                    required: $(e).attr('require'),
                    order_id: order_id,
                    value: productForm.val(),
                    record_value: productForm.val()
                }
            }
            if (productForm.attr('productForm') == 'select') {
                var obj = {
                    property_id: $(e).attr('property_id'),
                    name: $(e).attr('name'),
                    fixed_name: $(e).attr('name'),
                    required: $(e).attr('require'),
                    order_id: order_id,
                    content_ids: productForm.find('option:selected').val(),
                    value: productForm.find('option:selected').val() ? productForm.find('option:selected').text() : '',
                    record_value: productForm.find('option:selected').val() ? productForm.find('option:selected').text() : ''
                }
            }
            if (productForm.attr('productForm') == 'radio') {
                var content_ids = "";
                var value = "";
                var record_value = "";
                $.each(productForm, function (ii, ee) {
                    if ($(ee).is(":checked")) {
                        content_ids = $(ee).val();
                        value = $(ee).parent('label').text();
                        record_value = $(ee).parent('label').text();
                    }
                })
                var obj = {
                    property_id: $(e).attr('property_id'),
                    name: $(e).attr('name'),
                    fixed_name: $(e).attr('name'),
                    required: $(e).attr('require'),
                    order_id: order_id,
                    content_ids: content_ids,
                    value: value,
                    record_value: record_value
                }
            }
            if (productForm.attr('productForm') == 'textarea') {
                var obj = {
                    property_id: $(e).attr('property_id'),
                    name: $(e).attr('name'),
                    fixed_name: $(e).attr('name'),
                    required: $(e).attr('require'),
                    order_id: order_id,
                    value: productForm.val(),
                    record_value: productForm.val()
                }
            }
            if (productForm.attr('productForm') == 'checkbox') {
                var content_ids = "";
                var value = "";
                var record_value = "";
                $.each(productForm, function (ii, ee) {
                    if ($(ee).is(":checked")) {
                        content_ids += $(ee).val() + ',';
                        value += $(ee).parent('label').text() + ',';
                        record_value += $(ee).parent('label').text() + ',';
                    }
                })
                content_ids = content_ids.substring(0, content_ids.length - 1)
                value = value.substring(0, value.length - 1)
                record_value = record_value.substring(0, record_value.length - 1)
                var obj = {
                    property_id: $(e).attr('property_id'),
                    name: $(e).attr('name'),
                    fixed_name: $(e).attr('name'),
                    required: $(e).attr('require'),
                    order_id: order_id,
                    content_ids: content_ids,
                    value: value,
                    record_value: record_value
                }
            }
            //if (obj.required == '1' || obj.value != '') {
            productInfos.push(obj);
            //}
        })


        var productFeeInfos = new Array();

        var charging = $("input[fee_id]");

        $.each(charging, function (i, e) {
            var obj = {
                fee_id: $(e).attr("fee_id"),
                name: $(e).attr('name'),
                fixed_name: $(e).attr('name'),
                required: $(e).attr('require'),
                order_id: order_id,
                fee: $(e).val(),
                record_value: $(e).val()
            }
            productFeeInfos.push(obj);
        })


        var loanInfos = new Array();

        var loan = $("input[loan_id]:checked");
        if (loan.length) {
            loanInfos.push({
                loan_id: loan.attr("loan_id"),
                order_id: order_id,
                required: '1',
                value: loan.parent('label').text(),
                record_value: loan.parent('label').text()
            })
        }

        var orderInfos = new Array();

        var column = $("[column_key]")
        $.each(column, function (i, e) {
            if ($(e).attr('column_key') == 'loan_way') {
                var value = $(e).find('input[type="radio"]:checked').val();
                var record_value = $(e).find('input[type="radio"]:checked').parent('label').text();
                var obj = {
                    order_id: order_id,
                    column_key: $(e).attr('column_key'),
                    name: $(e).attr('name'),
                    fixed_name: $(e).attr('name'),
                    required: $(e).attr('require'),
                    value: value ? value : "",
                    record_value: record_value
                }
            }
            else if ($(e).attr('column_key') == 'apply_money') {
                var obj = {
                    order_id: order_id,
                    column_key: $(e).attr('column_key'),
                    name: $(e).attr('name'),
                    fixed_name: $(e).attr('name'),
                    required: $(e).attr('require'),
                    value: parseInt(Constant.fn.toNum($(e).val())) ? parseInt(Constant.fn.toNum($(e).val())) : "",
                    record_value: parseInt(Constant.fn.toNum($(e).val()))
                }
            }
            else if ($(e).attr('column_key') == 'loandays') {
                var obj = {
                    order_id: order_id,
                    column_key: 'at_id',
                    name: $(e).attr('name'),
                    fixed_name: $(e).attr('name'),
                    required: $(e).attr('require'),
                    value: $(e).val() ? $(e).val() : "",
                    record_value: $(e).val()
                }
            }
            else if ($(e).attr('column_key') == 'interest') {
                var obj = {
                    order_id: order_id,
                    column_key: $(e).attr('column_key'),
                    name: $(e).attr('name'),
                    fixed_name: $(e).attr('name'),
                    required: $(e).attr('require'),
                    value: $(e).val(),
                    record_value: $(e).val()
                }
            }
            else {
                var option = $(e).find('option:selected');
                var obj = {
                    order_id: order_id,
                    column_key: $(e).attr('column_key'),
                    name: $(e).attr('name'),
                    fixed_name: $(e).attr('name'),
                    required: $(e).attr('require'),
                    value: option.data('id') ? option.data('id') : "",
                    record_value: option.data('id') ? option.text() : ""
                }
            }
            //if (obj.required == '1' || obj.value != '') {
            orderInfos.push(obj);
            //}
        })

        var frontData = {
            productInfos: productInfos,
            productFeeInfos: productFeeInfos,
            orderInfos: orderInfos
        }

        var productInfos = frontData.productInfos;
        var productFeeInfos = frontData.productFeeInfos;
        var orderInfos = frontData.orderInfos;


        for (var i = 0; i < productInfos.length; i++) {
            if (productInfos[i].required == '1' && !productInfos[i].value) {
                Constant.fn.Message('I', '请填写' + productInfos[i].name);
                return;
            }
        }

        for (var i = 0; i < productFeeInfos.length; i++) {
            if (productFeeInfos[i].required == '1' && !productFeeInfos[i].fee) {
                Constant.fn.Message('I', '请填写' + productFeeInfos[i].name);
                return;
            }
        }

        for (var i = 0; i < orderInfos.length; i++) {
            if (orderInfos[i].required == '1' && !orderInfos[i].value && orderInfos[i].column_key != 'at_id') {
                Constant.fn.Message('I', '请填写' + orderInfos[i].name);
                return;
            }
            if (orderInfos[i].column_key == 'at_id' && !orderInfos[i].value && orderInfos[0].value != '4') {
                Constant.fn.Message('I', '请填写' + orderInfos[i].name);
                return;
            }
        }

        //验证是否选择角色
        if (approvalType == '2') {
            var userId = "";
            $.each($('.choose-per'), function (i, e) {
                userId += $(e).data('userid') + ',';
            })
            userId = userId.substring(0, userId.length - 1);
        }
        else {
            var userId = $("#role_select option:selected").val();
        }
        var type = $("input[name='faceResult']:checked").val();
        var remark = $(".approveRemark").val();
        if (last_node_id != node_id) {
            if (type == '1' && !userId) {
                Constant.fn.Message('I', '请选择审批角色');
                return;
            }
        }
        if (!type) {
            Constant.fn.Message('I', '请选择审核结果');
            return;
        }
        if (!remark) {
            Constant.fn.Message('I', '请输入备注');
            return;
        }
        ;

        site.send({
            url: url.saveNodefromInfos,
            data: {
                frontData: JSON.stringify(frontData)
            },
            callback: function (data) {
                data = JSON.parse(data)
                if (data.type == '1') {
                    saveImg(userId, type, remark);
                    //roamTask(userId, type, remark);
                } else {
                    Constant.fn.Message("F", data.msg);
                }
            }
        })
    }

    //流转
    function roamTask(userId, type, remark) {
        //console.log(flag);
        var data = {
            taskId: taskId,
            userId: userId,
            orderId: order_id,
            remark: remark,
            type: type
        }
        site.send({
            url: url.roamTask,
            data: data,
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {
                    $('.processForm_winBox').toggle();
                    Constant.fn.Message('T', data.msg);
                    pjaxReload();
                } else {
                    Constant.fn.Message("F", data.msg)
                }
            },
            callError: function () {

            }
        })
    }

    //查询出委托人列表
    function queryDelegate(current) {
        site.send({
            url: url.ChoiceOfclient,
            data: {
                pageNum: current
            },
            callback: function (data) {
                data = JSON.parse(data)
                if (data.type == 1) {
                    var source = $("#delegate_role_list_tpl").html();
                    var template = Handlebars.compile(source);
                    var list = data.content
                    var html = template(list)
                    $('.delegate_role_list').html(html)

                    $('.delegate-role-page-container').createPager({
                        current: frontData.pageNum,
                        total: data.content.total,
                        pageSize: data.content.pageSize,
                        needInput: false,
                        backFn: function (current) {
                            queryDelegate(current);
                        }
                    })
                }
                else {
                    Constant.fn.Message("F", data.msg)
                }
            }
        })
    }

    //查询订单表
    function salesManCheck() {
        var data = {
            roleId: Constant.getAurlparam("roleId"),
            audit_status: getAurlparam("t"),
            pageNum: frontData.pageNum,
            susp_status: '1'
        }
        if ($("#beginTime").val()) {
            data.beginTime = $("#beginTime").val()
        }
        if ($("#endTime").val()) {
            data.endTime = $("#endTime").val()
        }
        if ($("#seleNames option:selected").val()) {
            data.type = $("#seleNames option:selected").val()
        }
        if ($("#inputNames").val()) {
            data.keyword = $("#inputNames").val();
        }
        if ($("#at_id option:selected").val()) {
            data.atId = $("#at_id option:selected").val()
        }
        if ($("#loan_way option:selected").val()) {
            data.loan_way = $("#loan_way option:selected").val()
        }
        if ($("#product_choose_list").val()) {
            data.product_id = $("#product_choose_list").val()
        }
        site.send({
            url: url.queryOrder,
            data: data,
            callback: function (data) {
                data = JSON.parse(data)
                if (data.type == 1) {
                    if (data.content) {
                        $('.order-page-container').createPager({
                            current: frontData.pageNum,
                            total: data.content.total,
                            pageSize: data.content.pageSize,
                            needInput: false,
                            backFn: function (current) {
                                frontData.pageNum = current;
                                salesManCheck();
                            }
                        })
                        $('.result').html(data.content.total ? data.content.total : 0);
                    }
                    //handlebars模板引擎
                    var source = $("#order_list_tpl").html()
                    var template = Handlebars.compile(source)
                    var content = data.content;

                    var menuIndex = getAurlparam('h') || 0;
                    var thirdMenusIndex = getAurlparam('t') || 0;
                    var leftIndex = getAurlparam('i') || 0;

                    var storageContent = JSON.parse(localStorage.getItem('content'));

                    var obj = {
                        content: content,
                        fourthMenus: storageContent.menus[menuIndex].children[leftIndex].children[thirdMenusIndex].children || {}
                    }
                    var html = template(obj)
                    $('#order_list').html(html)

                    //复选框一个没选中则全选去除
                    $.each($("input[name='ch_id']"), function (i, e) {
                        var flag = false;
                        $(e).on('click', function () {
                            var _checked = $("input[name='ch_id_all']")
                            var _checkedAll = $("input[name='ch_id']")
                            $.each(_checkedAll, function (ii, ee) {
                                if ($(ee).prop('checked')) {
                                    flag = true
                                }
                                else {
                                    flag = false
                                    return false;
                                }
                            })
                            _checked.prop('checked', flag);
                        })
                    })


                    //渲染出模板后在进行操作
                    $(".operations").on('change', function () {
                        var choice = $(this).val();
                        product_id = $(this).attr('product_id');
                        order_id = $(this).attr('order_id');
                        taskId = $(this).attr('task_id');
                        node_type = $(this).attr('node_type')
                        node_id = $(this).attr('node_id')
                        s_id = $(this).attr('s_id');
                        repayment_way = $(this).attr('repayment_way');
                        at_id = $(this).attr('at_id');
                        if (choice == 'loanBeforeEditOrder') {
                            pjaxGo("loanBefore/orderEdit.html?order_id=" + order_id + "&product_id=" + product_id + "&task_id=" + taskId + "&node_id=" + node_id + "&s_id=" + s_id + "&repayment_way=" + repayment_way);
                        }
                        else if (choice == 'checkOrder') {
                            pjaxGo("loanBefore/orderDetail.html?order_id=" + order_id + "&product_id=" + product_id + "&task_id=" + taskId + "&node_id=" + node_id + "&s_id=" + s_id);
                        }
                        else if (choice == 'reviewOrder') {
                            if (node_type !== 3) {
                                $('.formBox .attachment').remove();
                                $('.formBox .productInfos').remove();
                                $('.formBox .fix').remove();
                                $('input[name="faceResult"]').prop('checked', false);
                                $('.role').remove();
                                $('.chooseRole').remove();
                                $('.approveRemark').val('');
                                $('.processForm_winBox').toggle();
                                getLastNodeId(product_id)
                                /*selectAttachmentType(node_id, product_id)*/
                                queryNodeForm(order_id, node_id, product_id)
                            }
                        }
                        else if ($(this).val() == 'orderDelegate') {
                            $('.delegate_winBox').toggle();
                            queryDelegate(1);
                        }
                        else if ($(this).val() == 'backReview') {
                            arr = [{
                                taskId: taskId,
                                orderId: order_id,
                                nodeId: node_id
                            }]
                            $('.backRemark').val("");
                            $('.backProcess_winBox').toggle();
                        }
                        else if ($(this).val() == 'lookProcess') {
                            $('.processBox').remove()
                            site.send({
                                url: url.getActivitiProccessImage,
                                data: {
                                    taskId: taskId,
                                },
                                callback: function (data) {
                                    data = JSON.parse(data)
                                    if (data.type == 1) {
                                        var source = $("#process_list_tpl").html();
                                        var template = Handlebars.compile(source);
                                        var list = data.content
                                        var html = template(list)
                                        $('.lookProcess').append(html)
                                        $('.lookProcess_winBox').toggle();
                                    }
                                    else {
                                        Constant.fn.Message("F", data.msg);
                                    }
                                }
                            })
                            //queryDelegate(1);
                        }
                        else if ($(this).val() == 'submitVisit') {
                            Common.visit(order_id);
                            Common.init(3, order_id);
                        }
                        else if ($(this).val() === 'addMaterial') {
                            site.send({
                                url: url.selectAttachmentWait,
                                data: {
                                    productId: product_id,
                                    roleId: getAurlparam('roleId'),
                                    oid: order_id
                                },
                                callback: function (data) {
                                    data = JSON.parse(data)
                                    if (data.type == 1) {
                                        var source = $("#material_list_tpl").html();
                                        var template = Handlebars.compile(source);
                                        var list = data.content;

                                        node_id = data.content.node_id;

                                        var html = template(list);
                                        $('#material_list').html(html);
                                        $('.addMaterial_winBox').toggle();

                                        $('.addMaterial_winBox .winBox1').viewer('destroy').viewer();
                                        Constant.fn.initScroll();

                                        OSS_IMAGE_INIT(order_id, node_id);

                                        //删除单张图片
                                        $('.delSingleAttach').unbind().on('click', function (e) {
                                            e.stopPropagation();
                                            e.preventDefault();
                                            $(this).parents('li').remove();
                                            Constant.fn.initScroll();
                                        })
                                    }
                                    else {
                                        Constant.fn.Message("F", data.msg);
                                    }
                                }
                            })
                        }
                        $(this).find("option:first").attr("selected", false).attr("selected", true);
                    });

                    Public.record('t_order_public');

                } else {
                    Constant.fn.Message("F", data.msg);
                }
            },
            callError: function () {
                alert("error")
            }
        })
    }

    //选择委托人的搜索按钮
    $('.showPerson').on('click', function () {
        var data = {
            pageNum: 1
        }
        if ($("#choice").val()) {
            data.name = $("#choice").val()
        }
        site.send({
            url: url.ChoiceOfclient,
            data: data,
            callback: function (data) {
                data = JSON.parse(data)
                if (data.type == 1) {
                    var source = $("#delegate_role_list_tpl").html();
                    var template = Handlebars.compile(source);
                    var list = data.content
                    var html = template(list)
                    $('.delegate_role_list').html(html)

                    $('.delegate-role-page-container').createPager({
                        current: frontData.pageNum,
                        total: data.content.total,
                        pageSize: data.content.pageSize,
                        needInput: false,
                        backFn: function (current) {
                            queryDelegate(current);
                        }
                    })
                }
                else {
                    Constant.fn.Message("F", data.msg)
                }
            }
        })
    })

    //确认委托
    $("#delegate").on('click', function () {
        var assignee = $(".delegate_role_list input[type='radio']:checked").val();
        if (!assignee) {
            Constant.fn.Message("I", "请选择委托人");
        }
        site.send({
            url: url.entrustOrder,
            data: {
                taskId: taskId,
                assignee: assignee,
                oid: order_id
            },
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == '1') {
                    $('.delegate_winBox').toggle();
                    Constant.fn.Message("T", data.msg)
                    pjaxReload();
                }
                else {
                    Constant.fn.Message("F", data.msg);
                }
            }
        })
    })

    //退回审核弹窗操作
    $('.sureBack').on('click', function () {
        var remark = $('.backRemark').val();
        if (!remark) {
            Constant.fn.Message('I', '请输入备注');
            return;
        }
        site.send({
            url: url.backProcess,
            data: {
                backParameters: JSON.stringify(arr),
                remark: remark
            },
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {
                    $('.backProcess_winBox').toggle();
                    Constant.fn.Message('T', data.msg);
                    pjaxReload();
                    //salesManCheck();
                    //location.reload();
                    //salesManCheck();
                }
                else {
                    Constant.fn.Message('F', data.msg);
                }
            }
        })
    })

    //资料补全按钮
    $("#sureAddMaterial").on('click',function(){
        var ajaxLength = $('.addMaterial_winBox [attachid]').length;
        if (ajaxLength) {
            $.each($('.addMaterial_winBox [attachid]'), function (i, e) {
                var data = {
                    attachImg: "",
                    attachName: $(e).attr('attachname'),
                    attachId: $(e).attr('attachid'),
                    oid: order_id,
                    //oid: 1,
                    productId: product_id,
                    nodeId: node_id,
                    //nodeId: 2,
                    order_num: order_num,
                    //s_id: '1'
                    //type: $(e).parents('td').find('input[type="radio"]:checked').val()
                }
                if($(e).attr('attachid') == '65'){
                    data.is_target = 1;
                }else{
                    data.is_target = -1;
                }
                var attachImg = [];
                $.each($(e).find('li'), function (ii, ee) {
                    attachImg.push($(ee).attr('href'));
                })

                $.each($(e).parents('td').find('[fileattachid]').find('a'), function (iii, eee) {
                    attachImg.push($(eee).attr('href'));
                })

                if (attachImg.length) {
                    data.attachImg = JSON.stringify(attachImg)
                }

                site.send({
                    url: url.insertAttachment,
                    data: data,
                    callback: function (data) {
                        data = JSON.parse(data)
                        if (data.type == 1) {
                            ajaxLength -= 1;
                            if (ajaxLength === 0) {
                                $(".addMaterial_winBox").toggle();
                                //roamTask(userId, type, remark);
                                Constant.fn.Message("T", data.msg);
                            }
                        }
                    }
                })
            })
        } else {
            $(".addMaterial_winBox").toggle();
            //roamTask(userId, type, remark);
        }
    })

    $('.canBack').on('click', function () {
        $('.backProcess_winBox').toggle();
    })


    //节点表单审核单选按钮
    $('input[name="faceResult"][value="1"]').unbind().on('change', function () {
        queryRole(order_id);
    })

    $('input[name="faceResult"][value="2"]').unbind().on('change', function () {
        $('.role').remove();
        $('.chooseRole').remove();
    })

    //搜索功能
    $(".sousuo").on('click', function () {
        frontData.pageNum = 1;
        salesManCheck();
    })

    //获取流程的最后一个节点，判断是否处在流程最后一步
    function getLastNodeId(product_id) {
        site.send({
            url: url.queryEndNodeId,
            data: {
                product_id: product_id,
            },
            callback: function (data) {
                data = JSON.parse(data)
                if (data.type == 1) {
                    last_node_id = data.content.node_id;
                }
                else {
                    Constant.fn.Message("F", data.msg);
                }
            }
        })
    }

    $(document).on('click', '.icon-wrong', function () {
        $(this).parents('.winBox').hide();
    })

    //点击流转保存图片
    function saveImg(userId, type, remark) {
        var ajaxLength = $('.processForm_winBox [attachid]').length;
        if (ajaxLength) {
            $.each($('.processForm_winBox [attachid]'), function (i, e) {
                var data = {
                    attachImg: "",
                    attachName: $(e).attr('attachname'),
                    attachId: $(e).attr('attachid'),
                    oid: order_id,
                    //oid: 1,
                    productId: product_id,
                    nodeId: node_id,
                    //nodeId: 2,
                    order_num: order_num,
                    //s_id: '1'
                    //type: $(e).parents('td').find('input[type="radio"]:checked').val()
                }

                if($(e).attr('attachid') == '65'){
                    data.is_target = 1;
                }else{
                    data.is_target = -1;
                }

                var attachImg = [];
                $.each($(e).find('li'), function (ii, ee) {
                    attachImg.push($(ee).attr('href'));
                })

                $.each($(e).parents('td').find('[fileattachid]').find('a'), function (iii, eee) {
                    attachImg.push($(eee).attr('href'));
                })

                if (attachImg.length) {
                    data.attachImg = JSON.stringify(attachImg)
                }

                site.send({
                    url: url.insertAttachment,
                    data: data,
                    callback: function (data) {
                        data = JSON.parse(data)
                        if (data.type == 1) {
                            ajaxLength -= 1;
                            if (ajaxLength === 0) {
                                roamTask(userId, type, remark);
                            }
                        }
                    }
                })
            })
        } else {
            roamTask(userId, type, remark);
        }
    }

    //点击流转
    $("#roamTask").click(function (e) {
        e.stopPropagation();
        saveNodefromInfos();
        //saveImg();
        //roamtask(userId);
    })

    salesManCheck();

    /*//查询已审核与未审核
        $(".public-List").on('click', function () {
            $('.public-List').removeClass('publicListHover');
            $(this).addClass('publicListHover')
            salesManCheck();
        })*/


    //录入订单
    $("#orderIn").on('click', function () {
        pjaxGo("loanBefore/product_orderIn.html");
    })

    //流转查询出角色
    function queryRole(order_id) {
        site.send({
            url: url.queryAdminRoleByRole,
            data: {
                order_id: order_id
            },
            callback: function (data) {
                data = JSON.parse(data)
                if (data.type == 1) {
                    var source = $("#role_list_tpl").html();
                    var template = Handlebars.compile(source);
                    var list = data.content
                    var html = template(list)
                    $('.role_list').append(html)

                    if (data.content) {
                        approvalType = data.content.approvalType;
                    }

                    //下拉框选中获取值
                    $("#role_select").on('change', function () {
                        userId = $(this).find("option:selected").val();
                        if (approvalType == '2') {
                            var flag = true;
                            if ($(this).val()) {
                                var userName = $(this).find("option:selected").text();
                                $('.chooseRole').show();
                                if (!$('.choose-per').length) {
                                    $('.chooseRole .selPers').append('<span data-userid= ' + userId + ' class="choose-per"><span class="choose-perName">' + userName + '</span><span class="removeRole" style="cursor: pointer;">×</span></span>');
                                }
                                else {
                                    $.each($('.choose-per'), function (i, e) {
                                        //console.log()
                                        console.log($(e).data('userid'));
                                        if (userId == $(e).data('userid')) {
                                            //$('.chooseRole .selPers').append('<span data-userid= ' + userId + ' class="choose-per"><span class="choose-perName">' + userName + '</span><span class="removeRole" style="cursor: pointer;">×</span></span>');
                                            flag = false;
                                        }
                                    })
                                    if (flag) {
                                        $('.chooseRole .selPers').append('<span data-userid= ' + userId + ' class="choose-per"><span class="choose-perName">' + userName + '</span><span class="removeRole" style="cursor: pointer;">×</span></span>');
                                    }
                                }
                            }
                            $('.removeRole').unbind().on('click', function () {
                                $(this).parents('.choose-per').remove();
                                console.log($(this).parents('td'));
                                if ($('.selPers').find('.choose-per').length == 0) {
                                    $(".chooseRole").hide();
                                    $("#role_select").val('');
                                }
                            })
                        }
                    })
                }
                else {
                    var source = $("#role_list_tpl").html();
                    var template = Handlebars.compile(source);
                    var list = data.content
                    var html = template(list)
                    $('.role_list').append(html)
                    Constant.fn.Message('F', data.msg);
                    //$('.processForm_winBox').toggle();
                }
            }
        })
    }


    function initformSelect(content) {
        site.send({
            url: url.selectLoanTypeList,
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {
                    var source = $("#loanType_content_tpl").html();
                    var template = Handlebars.compile(source);
                    var html = template(data.content);
                    $('#loanType_content').html(html);

                    var orderInfos = content.orderInfos;
                    $.each(orderInfos, function (i, e) {
                        if (e.fixed_key == "lt_id") {
                            if (e.is_edit == 1) {
                                $("#loanType_content option[data-id=" + e.real_data + "]").attr("selected", true)
                            }
                            else {
                                $("#loanType_content").parents('td').html($("#loanType_content option[data-id=" + e.real_data + "]").text());
                            }
                        }
                    })
                }
                else {
                    Constant.fn.Message("F", data.msg)
                }
            }
        })

        site.send({
            url: url.selectApplyTermList,
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {
                    var source = $("#applyTerm_content_tpl").html();
                    var template = Handlebars.compile(source);
                    applyHtml = template(data.content);
                    $('#applyTerm_content').html(applyHtml);
                    var source = $("#at_id_tpl").html();
                    var template = Handlebars.compile(source);
                    var html = template(data.content);
                    $('#at_id').html(html);


                    var orderInfos = content.orderInfos;
                    $.each(orderInfos, function (i, e) {
                        if (e.fixed_key == "at_id") {
                            if (e.is_edit == 1) {
                                $("#applyTerm_content option[data-id=" + e.real_data + "]").attr("selected", true)
                            }
                            else {
                                $("#applyTerm_content").parents('td').html($("#applyTerm_content option[data-id=" + e.real_data + "]").text());
                            }
                        }
                    })
                }
                else {
                    Constant.fn.Message("F", data.msg)
                }
            }
        })

        site.send({
            url: url.selectRepanymentWayList,
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {
                    var source = $("#repanymentWay_content_tpl").html();
                    var template = Handlebars.compile(source);
                    var html = template(data.content);
                    $('#repanymentWay_content').html(html);

                    var orderInfos = content.orderInfos;
                    $.each(orderInfos, function (i, e) {
                        if (e.fixed_key == "repayment_way") {
                            if (e.is_edit == 1) {
                                $("#repanymentWay_content option[data-id=" + e.real_data + "]").attr("selected", true)
                            }
                            else {
                                var real_data = $("#repanymentWay_content option[data-id=" + e.real_data + "]").text()
                                real_data ? $("#repanymentWay_content").parents('td').html(real_data) : "未填写";
                            }
                            if (real_data == '4') {
                                $('.applyTrem').hide();
                            }
                        }
                    })
                }
                else {
                    Constant.fn.Message("F", data.msg)
                }
            }
        })

        site.send({
            url: url.selectOrderSourceList,
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {
                    var source = $("#orderSource_content_tpl").html();
                    var template = Handlebars.compile(source);
                    var html = template(data.content);
                    $('#orderSource_content').html(html);

                    var orderInfos = content.orderInfos;
                    $.each(orderInfos, function (i, e) {
                        if (e.fixed_key == "os_id") {
                            if (e.is_edit == 1) {
                                $("#orderSource_content option[data-id=" + e.real_data + "]").attr("selected", true)
                            }
                            else {
                                var real_data = $("#orderSource_content option[data-id=" + e.real_data + "]").text()
                                real_data ? $("#orderSource_content").parents('td').html(real_data) : "未填写";
                            }
                        }
                        if (e.fixed_key == "apply_money") {
                            if (e.is_edit == 1) {
                                $("#apply_money").val(e.real_data);
                            }
                            else {
                                $("#apply_money").parents('td').html(e.real_data + "元");
                            }
                        }
                    })
                }
                else {
                    Constant.fn.Message("F", data.msg)
                }
            }
        })

        site.send({
            url: url.queryLoanDefineByProductId,
            data: {
                product_id: product_id
            },
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {
                    var source = $("#loanMethod_content_tpl").html();
                    var template = Handlebars.compile(source);
                    var html = template(data.content);
                    $('#loanMethod_content').append(html);

                    var orderInfos = content.orderInfos;
                    $.each(orderInfos, function (i, e) {
                        if (e.fixed_key == "loan_way") {
                            if (e.is_edit == 1) {
                                $("#loanMethod_content input[value=" + e.real_data + "]").prop("checked", true);
                            }
                            else {
                                $("#loanMethod_content input[value=" + e.real_data + "]").prop("checked", true);
                                $("#loanMethod_content").parents('tr').html($('#loanMethod_content input[type="radio"]:checked').text());
                            }
                        }
                    })
                }
                else {
                    Constant.fn.Message("F", data.msg)
                }
            }
        })
    }

    /*//流转查询出附件类型
    function selectAttachmentType(node_id, product_id) {
        site.send({
            url: url.selectAttachmentType,
            data: {
                productId: product_id,
                nodeId: node_id
            },
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {
                    var source = $("#attachmentType_tpl").html();
                    var template = Handlebars.compile(source);
                    var list = data.content;
                    var html = template(list);
                    $('.formBox .approve').before(html);

                    OSS_IMAGE_INIT(order_id, node_id);
                }
            }
        })
    }*/

    //流转查询出表单
    function queryNodeForm(order_id, node_id, product_id) {
        site.send({
            url: url.queryNodeFromInfoAllByONid,
            data: {
                node_id: node_id,
                order_id: order_id,
                product_id: product_id
            },
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {
                    //handlebars模板引擎
                    var source = $("#form_list_tpl").html()
                    var template = Handlebars.compile(source)
                    var content = data.content
                    var html = template(content)
                    $('.formBox .approve').before(html)
                    $('#apply_money').on({
                        'focus': function () {
                            $(this).val(Constant.fn.toNum($(this).val()));
                        },
                        'blur': function () {
                            $(this).val(Constant.fn.toRMB($(this).val()));
                        }
                    })

                    //还款方式改变
                    $("#repanymentWay_content").on('change', function () {
                        if ($(this).find('option:selected').data('id') == '4') {
                            $('.applyTrem').eq(0).html('<span style="color:red">*</span>申请天数');
                            $('.applyTrem').eq(1).html('<label><input type="text" autocomplete="off" require="1" id="days" name="申请天数" column_key="loandays" class="ng-pristine ng-untouched ng-valid ng-empty">天\n' +
                                '                </label>').removeClass('tdSelect').addClass('tdWei');
                        } else {
                            $('.applyTrem').eq(0).html('<span style="color:red">*</span>申请期限');
                            $('.applyTrem').eq(1).html('<div class="se-re"><select id="applyTerm_content" name="申请期限" require="1" column_key="at_id" class="ng-pristine ng-valid ng-empty ng-touched">' + applyHtml + '</select></div>').addClass('tdSelect').removeClass('tdWei');
                        }
                    })

                    $('.processForm_winBox .winBox1').viewer('destroy').viewer();
                    Constant.fn.initScroll();

                    OSS_IMAGE_INIT(order_id, node_id);
                    //UploadImage.OSS_IMAGE_INIT(order_id,node_id);

                    //删除单张图片
                    $('.delSingleAttach').unbind().on('click', function (e) {
                        e.stopPropagation();
                        e.preventDefault();
                        $(this).parents('li').remove();

                        Constant.fn.initScroll();
                    })

                    //渲染真实数据
                    initformSelect(content);
                    if (repayment_way == '4') {
                        $('.applyTrem').eq(0).html('<span style="color:red">*</span>申请天数');
                        $('.applyTrem').eq(1).html('<label><input type="text" autocomplete="off" require="1" value=' + at_id + ' id="days" name="申请天数" column_key="loandays" class="ng-pristine ng-untouched ng-valid ng-empty">天\n' +
                            '                </label>').removeClass('tdSelect').addClass('tdWei');
                    }
                }
            }
        })
    }

    //批量操作

    $("#bulk_operation").on('change', function () {

        //console.log(1);
        /*odata = "";
        otask_id = "";
        onode_id = "";*/
        arr = [];

        var selected = $(this).find("option:selected");
        $(this).find("option:first").prop("selected", false).prop("selected", true);
        $("input[name='ch_id']:checked").each(function (index, item) {
            /*odata = odata + $(item).val() + ","
            otask_id = otask_id + $(item).data('taskid') + ","
            onode_id = onode_id + $(item).data('nodeid') + ","*/
            arr.push({
                taskId: $(item).data('taskid'),
                orderId: $(item).val(),
                nodeId: $(item).data('nodeid')
            })
        })
        /*odata = odata.substring(0, odata.length - 1);
        otask_id = otask_id.substring(0, otask_id.length - 1);
        onode_id = onode_id.substring(0, onode_id.length - 1);*/
        if (selected.val() == '批量退回') {
            //删除产品
            if (!arr.length) {
                Constant.fn.Message('I', "未选择要退回的订单")
                return;
            }
            $('.backRemark').val("");
            $('.backProcess_winBox').toggle();
        }
    })

    $('.sureDel').on('click', function () {
        site.send({
            url: url.delOrderAll,
            data: {
                taskId: taskId,
                orderId: odata,
                nodeId: node_id,
            },
            callback: function (data) {
                data = JSON.parse(data)
                if (data.type == 1) {
                    $('.delete_winBox').toggle();
                    Constant.fn.Message('T', data.msg);
                    pjaxReload();
                } else {
                    Constant.fn.Message("F", data.msg)
                }
            },
            callError: function () {

            }
        })
    })


    $('.canDel').on('click', function () {
        $('.delete_winBox').toggle();
    })
    $('.headerIcon').on('click', function () {
        $(this).parents('.delete_winBox').toggle();
    })

    $(".datepicker").datepicker({
        format: 'yyyy-mm-dd',
        autoclose: true
    })

    //上传图片是否显示左右箭头初始化
    Constant.fn.initScroll();


    // WebUploader实例
    var uploader;
    var attachId, attachName, order_num;
    var type;
    var success = false;


    function OSS_IMAGE_INIT(order_id, node_id) {

        var objdata = {
            upfile_nametype: 'random_name',//local_name random_name  上传文件的文件名类型
            url: localStorage.getItem('host') + "oss/getSignature.do"
        };
        // 当domReady的时候开始初始化
        $(".viewPic").unbind().on('click', function () {
            type = $(this).siblings('._result').find('input[type=radio]:checked').val()
            attachId = $(this).data('id');
            attachName = $(this).data('attachname');
            order_num = $('.public-content-Po').html();

            /*if (!order_id) {
                Constant.fn.Message('I', '请先录入订单');
                //$("#viewPic").unbind();
                return
            }*/

            /*if(!attach_id){
                $("#attachmentType").addClass('error');
                Constant.fn.Message('I','请选择类型');
                return
            }*/

            timeout : 30000,
                $.ajax({
                    type: "post",
                    url: objdata.url,
                    success: function (str) {
                        data = JSON.parse(str)
                        if (data.type > 0) {
                            try {
                                var re = data.content;
                                objdata.osssignature = {
                                    'key': re.dir,
                                    'policy': re.policy,
                                    'OSSAccessKeyId': re.accessId,
                                    'success_action_status': '200', //让服务端返回200,不然，默认会返回204
                                    'signature': re.signature,
                                    'callback': re.callback,
                                    'expire': re.expire,
                                    'host': re.host
                                };
                            } catch (e) {
                                alert("系统错误");
                            }

                        } else {
                            alert("结果为空");
                        }
                        $("#image_upload_pop").toggle();

                        //设置居中
                        centerPosition($("#image_upload_pop .edui-dialog-body").get(0));
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        // alert("ajax error");
                    },
                    complete: function (XMLHttpRequest, status) { //请求完成后最终执行参数
                        if (status == 'timeout') {
                            //alert('请求超时，请稍后再试！');
                        }
                    },
                    async: false
                });

            //var state = 'pedding';

            if (uploader) {
                //setState('ready');
                //uploader.reset();
                return;
            }///界面已经存在，不去重新创建uploader了

            var $wrap = $('#uploader'),
                // 图片容器
                $queue = $('<ul class="filelist"></ul>').appendTo($wrap.find('.queueList')),

                // 状态栏，包括进度和控制按钮
                $statusBar = $wrap.find('.statusBar'),

                // 文件总体选择信息。
                $info = $statusBar.find('.info'),

                // 上传按钮
                $upload = $wrap.find('.uploadBtn'),

                // 没选择文件之前的内容。
                $placeHolder = $wrap.find('.placeholder'),

                $progress = $statusBar.find('.progress').hide(),

                // 添加的文件数量
                fileCount = 0,

                // 添加的文件总大小
                fileSize = 0,

                acceptExtensions = [".png", ".tif", ".TIF", ".pdf", ".doc", ".docx", ".jpg", ".jpeg", ".gif", ".bmp", ".xls", ".xlsx"].join('').replace(/\./g, ',').replace(/^[,]/, ''),

                // 优化retina, 在retina下这个值是2
                ratio = window.devicePixelRatio || 1,

                // 缩略图大小
                thumbnailWidth = 110 * ratio, thumbnailHeight = 110 * ratio,

                // 可能有pedding, ready, uploading, confirm, done.
                state = 'pedding',

                // 所有文件的进度信息，key为file id
                percentages = {},
                // 判断浏览器是否支持图片的base64
                isSupportBase64 = (function () {
                    var data = new Image();
                    var support = true;
                    data.onload = data.onerror = function () {
                        if (this.width != 1 || this.height != 1) {
                            support = false;
                        }
                    }
                    data.src = "";
                    return support;
                })(),

                // 检测是否已经安装flash，检测flash的版本
                flashVersion = (function () {
                    var version;

                    try {
                        version = navigator.plugins['Shockwave Flash'];
                        version = version.description;
                    } catch (ex) {
                        try {
                            version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version');
                        } catch (ex2) {
                            version = '0.0';
                        }
                    }
                    version = version.match(/\d+/g);
                    return parseFloat(version[0] + '.' + version[1], 10);
                })(),

                supportTransition = (function () {
                    var s = document.createElement('p').style,
                        r = 'transition' in s || 'WebkitTransition' in s || 'MozTransition' in s || 'msTransition' in s || 'OTransition' in s;
                    s = null;
                    return r;
                })(), _this = this;

            _this.imageList = [];
            if (!WebUploader.Uploader.support('flash') /* && WebUploader.browser.ie */) {

                // flash 安装了但是版本过低。
                if (flashVersion) {
                    (function (container) {
                        window['expressinstallcallback'] = function (state) {
                            switch (state) {
                                case 'Download.Cancelled':
                                    alert('您取消了更新！')
                                    break;

                                case 'Download.Failed':
                                    alert('安装失败')
                                    break;

                                default:
                                    alert('安装已成功，请刷新！');
                                    break;
                            }
                            delete window['expressinstallcallback'];
                        };

                        var swf = './expressInstall.swf';
                        // insert flash object
                        var html = '<object type="application/' + 'x-shockwave-flash" data="' + swf + '" ';

                        if (WebUploader.browser.ie) {
                            html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';
                        }

                        html += 'width="100%" height="100%" style="outline:0">' + '<param name="movie" value="' + swf + '" />' + '<param name="wmode" value="transparent" />' + '<param name="allowscriptaccess" value="always" />' + '</object>';

                        container.html(html);

                    })($wrap);

                    // 压根就没有安装。
                } else {
                    $wrap.html('<a href="http://www.adobe.com/go/getflashplayer" target="_blank" border="0"><img alt="get flash player" src="http://www.adobe.com/macromedia/style_guide/images/160x41_Get_Flash_Player.jpg" /></a>');
                }

                return;
            } else if (!WebUploader.Uploader.support()) {
                alert('Web Uploader 不支持您的浏览器！');
                return;
            }


            // 实例化
            uploader = WebUploader.create({
                pick: {
                    id: '#filePicker',
                    label: '点击选择图片'
                },
                resize: false,
                duplicate: true,
                accept: {
                    title: 'Images',
                    extensions: acceptExtensions,
                    // mimeTypes: 'filed/!*' //wuzhifeng 修改上传文件类型 图片的话 是
                    // image
                    mimeTypes: 'image/!*'
                },
                formData: {
                    uid: 123
                },
                dnd: '#edui114_body',
                paste: '#uploader',
                swf: '/tbpt/plugin/ueditor/third-party/webuploader/Uploader.swf',
                chunked: false,
                compress: false,
                chunkSize: 512 * 1024,
                server: objdata.osssignature.host,///tbpt/plugin/ueditor/jsp/controller.jsp?action=uploadimage
                //http://oss.aliyuncs.com/ http://tbptfile.oss-cn-beijing.aliyuncs.com/
                // runtimeOrder: 'flash',
                // server:
                // 'http://liaoxuezhi.fe.baidu.com/webupload/fileupload.php',
                // server: 'http://www.2betop.net/fileupload.php',
                //

                // accept: {
                // title: 'Images',
                // extensions: 'gif,jpg,jpeg,bmp,png',
                // mimeTypes: 'image/!*'
                // },

                // 禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候，把图片打开。
                disableGlobalDnd: false,
                auto: false,// {Boolean} [可选] [默认值：false] 设置为 true
                // 后，不需要手动调用上传，有文件选择即开始上传。
                fileNumLimit: 300,// 验证文件总数量, 超出则不允许加入队列。
                fileSizeLimit: 200 * 1024 * 1024, // 200 M
                fileSingleSizeLimit: 110 * 1024 * 1024 // 50 M
            });

            // 拖拽时不接受 js, txt 文件。
            uploader.on('dndAccept', function (items) {
                var denied = false, len = items.length, i = 0,
                    // 修改js类型
                    unAllowed = 'text/plain;application/javascript ';

                for (; i < len; i++) {
                    // 如果在列表里面
                    if (~unAllowed.indexOf(items[i].type)) {
                        denied = true;
                        break;
                    }
                }

                return !denied;
            });
            // 添加“添加文件”的按钮，
            uploader.addButton({
                id: '#filePicker2',
                label: '继续添加'
            });

            uploader.on('ready', function () {
                window.uploader = uploader;
            });

            //上传完成 服务器响应 不代表上传成功
            uploader.on('uploadSuccess', function (file, ret) {
                //console.log(fileCount);
                //console.log(responseText);
                var $file = $('#' + file.id);
                if (ret._raw) {
                    _this.imageList[$file.index()] = {
                        succ: true
                    };
                    $file.append('<span class="success"></span>');
                    //图片
                    if (file.type == 'image/jpeg' || file.type == 'image/png' || file.type == 'image/tiff') {
                        //console.log($file.index());
                        var index = $file.index();
                        /*if ($file.index() == 0) {
                            $('#picStay').prepend('原图:<a sort="' + $file.index() + '" playHref="' + objdata.osssignature.host + "/" + file.path + '/tupian_compress" href="' + objdata.osssignature.host + "/" + file.path + '" target="_blank" >' + objdata.osssignature.host + "/" + file.path + '</a>');
                            $('#picStay').prepend('<img sort="' + $file.index() + '" src="' + objdata.osssignature.host + "/" + file.path + '?x-oss-process=image/resize,m_lfit,h_56,w_36" />');
                        } else {*/
                        var aSortArr = [];
                        if (!$('#picStay a').length) {
                            $('#picStay').prepend('原图:<a sort="' + index + '" playHref="' + objdata.osssignature.host + "/" + file.path + '/tupian_compress" href="' + objdata.osssignature.host + "/" + file.path + '" target="_blank" >' + objdata.osssignature.host + "/" + file.path + '</a>');
                        } else {
                            $.each($('#picStay a'), function (i, e) {
                                if ($(e).attr('sort') < index) {
                                    aSortArr.push($(e).attr('sort'))
                                }
                            })

                            if (aSortArr.length) {
                                $("#picStay a").eq(aSortArr.length - 1).after('原图:<a sort="' + index + '" playHref="' + objdata.osssignature.host + "/" + file.path + '/tupian_compress" href="' + objdata.osssignature.host + "/" + file.path + '" target="_blank" >' + objdata.osssignature.host + "/" + file.path + '</a>');
                            }
                            else {
                                $('#picStay').prepend('原图:<a sort="' + index + '" playHref="' + objdata.osssignature.host + "/" + file.path + '/tupian_compress" href="' + objdata.osssignature.host + "/" + file.path + '" target="_blank" >' + objdata.osssignature.host + "/" + file.path + '</a>');
                            }
                        }


                        var imgSortArr = [];
                        if (!$('#picStay img').length) {
                            $('#picStay').prepend('<img sort="' + index + '" src="' + objdata.osssignature.host + "/" + file.path + '/tupian_compress" />');
                        } else {
                            $.each($('#picStay img'), function (i, e) {
                                if ($(e).attr('sort') < index) {
                                    imgSortArr.push($(e).attr('sort'))
                                }
                            })

                            if (imgSortArr.length) {
                                $("#picStay img").eq(imgSortArr.length - 1).after('<img sort="' + index + '" src="' + objdata.osssignature.host + "/" + file.path + '/tupian_compress" />');
                            } else {
                                $('#picStay').prepend('<img sort="' + index + '" src="' + objdata.osssignature.host + "/" + file.path + '/tupian_compress" />');
                            }
                        }


                        /*}*/
                        //$('#picStay').append('<img src="' + objdata.osssignature.host + "/" + file.path + '?x-oss-process=image/resize,m_fill,h_100,w_100" />');
                    }
                    else {
                        var index = $file.index();
                        /*if ($file.index() == 0) {
                            $('#picStay').prepend('原图:<a sort="' + $file.index() + '" playHref="' + objdata.osssignature.host + "/" + file.path + '/tupian_compress" href="' + objdata.osssignature.host + "/" + file.path + '" target="_blank" >' + objdata.osssignature.host + "/" + file.path + '</a>');
                            $('#picStay').prepend('<img sort="' + $file.index() + '" src="' + objdata.osssignature.host + "/" + file.path + '?x-oss-process=image/resize,m_lfit,h_56,w_36" />');
                        } else {*/
                        var aFileSortArr = [];
                        if (!$('#fileStay a').length) {
                            $('#fileStay').prepend('原图:<a sort="' + index + '" type="' + file.type + '" name="' + file.name + '" playHref="' + objdata.osssignature.host + "/" + file.path + '" href="' + objdata.osssignature.host + "/" + file.path + '" target="_blank" >' + objdata.osssignature.host + "/" + file.path + '</a>');
                        } else {
                            $.each($('#fileStay a'), function (i, e) {
                                if ($(e).attr('sort') < index) {
                                    aFileSortArr.push($(e).attr('sort'))
                                }
                            })

                            if (aFileSortArr.length) {
                                $("#fileStay a").eq(aFileSortArr.length - 1).after('原图:<a sort="' + index + '" type="' + file.type + '" name="' + file.name + '" playHref="' + objdata.osssignature.host + "/" + file.path + '" href="' + objdata.osssignature.host + "/" + file.path + '" target="_blank" >' + objdata.osssignature.host + "/" + file.path + '</a>');
                            }
                            else {
                                $('#fileStay').prepend('原图:<a sort="' + index + '" type="' + file.type + '" name="' + file.name + '" playHref="' + objdata.osssignature.host + "/" + file.path + '" href="' + objdata.osssignature.host + "/" + file.path + '" target="_blank" >' + objdata.osssignature.host + "/" + file.path + '</a>');
                            }
                        }


                        var fileSortArr = [];
                        if (!$('#fileStay img').length) {
                            $('#fileStay').prepend('<img sort="' + index + '" src="' + objdata.osssignature.host + "/" + file.path + '" />');
                        } else {
                            $.each($('#fileStay img'), function (i, e) {
                                if ($(e).attr('sort') < index) {
                                    fileSortArr.push($(e).attr('sort'))
                                }
                            })

                            if (fileSortArr.length) {
                                $("#fileStay img").eq(fileSortArr.length - 1).after('<img sort="' + index + '" src="' + objdata.osssignature.host + "/" + file.path + '" />');
                            } else {
                                $('#fileStay').prepend('<img sort="' + index + '" src="' + objdata.osssignature.host + "/" + file.path + '" />');
                            }
                        }
                    }
                } else {
                    showError(file.statusText);
                    $file.find('.error').text("失败").show();
                    console.log("上传失败");
                    $('body').append("上传失败");
                }

            });

            uploader.on('uploadBeforeSend', function (obj, data, headers) {
                //TODO   如果同一个页面上传多次  需要处理签名逻辑   不用每次都签名
                //debugger
                //赋值参数
                data = $.extend(data, objdata.osssignature);
                headers['Access-Control-Allow-Origin'] = "*";

                //设置文件路径
                data.key = data.key + "/" + calculate_object_name(data.name, objdata.upfile_nametype);
                obj.filepath = data.key;
                obj.file.path = data.key;
            });

            //得到文件名 type local_name random_name
            function calculate_object_name(filename, type) {
                if (type && type == 'local_name') {
                    return "${filename}";
                } else {//随机生成文件名
                    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
                    var maxPos = chars.length;
                    var random_string = '';
                    for (i = 0; i < 10; i++) {
                        random_string += chars.charAt(Math.floor(Math.random() * maxPos));
                    }
                    var pos = filename.lastIndexOf('.')
                    var suffix = ''
                    if (pos != -1) {
                        suffix = filename.substring(pos);
                    }
                    return random_string + new Date().getTime() + suffix;
                }
            }

            // 当有文件添加进来时执行，负责view的创建
            function addFile(file) {
                var $li = $('<li id="' + file.id + '">' + '<p class="title">' + file.name + '</p>' + '<p class="imgWrap"></p>' + '<p class="progress"><span></span></p>' + '</li>'),

                    $btns = $('<div class="file-panel">' + '<span class="cancel">删除</span>' + '<span class="rotateRight">向右旋转</span>' + '<span class="rotateLeft">向左旋转</span></div>').appendTo($li),
                    $prgress = $li.find('p.progress span'), $wrap = $li.find('p.imgWrap'),
                    $info = $('<p class="error"></p>'),

                    showError = function (code) {
                        switch (code) {
                            case 'exceed_size':
                                text = '文件大小超出';
                                break;

                            case 'interrupt':
                                text = '上传暂停';
                                break;

                            default:
                                text = '上传失败，请重试';
                                break;
                        }

                        $info.text(text).appendTo($li);
                    };

                if (file.getStatus() === 'invalid') {
                    showError(file.statusText);
                } else {
                    // @todo lazyload
                    $wrap.text('预览中');
                    uploader.makeThumb(file, function (error, src) {
                        var img;

                        if (error) {
                            $wrap.text('不能预览');
                            return;
                        }

                        if (isSupportBase64) {
                            img = $('<img src="' + src + '">');
                            $wrap.empty().append(img);
                        }
                    }, thumbnailWidth, thumbnailHeight);

                    percentages[file.id] = [file.size, 0];
                    file.rotation = 0;
                }


                file.on('statuschange', function (cur, prev) {
                    if (prev === 'progress') {
                        $prgress.hide().width(0);
                    } else if (prev === 'queued') {
                        $li.off('mouseenter mouseleave');
                        $btns.remove();
                    }
                    // 成功
                    if (cur === 'error' || cur === 'invalid') {
                        console.log(file.statusText);
                        showError(file.statusText);
                        percentages[file.id][1] = 1;
                    } else if (cur === 'interrupt') {
                        showError('interrupt');
                    } else if (cur === 'queued') {
                        percentages[file.id][1] = 0;
                    } else if (cur === 'progress') {
                        $info.remove();
                        $prgress.css('display', 'block');
                    } else if (cur === 'complete') {
                        //$li.append('<span class="success"></span>');
                    }

                    $li.removeClass('state-' + prev).addClass('state-' + cur);
                });
                uploader.on('uploadAccept', function (file, response) {
                    var hasError = (response['error'] !== undefined);
                    if (hasError) {
                        // 通过return false来告诉组件，此文件上传有错。
                        return false;
                    }
                    ;
                });
                uploader.on("uploadFinished", function () {
                    success = true;
                    // uploader.reset();
                    // uploader;
                });

                $li.on('mouseenter', function () {
                    $btns.stop().animate({
                        height: 30
                    });
                });

                $li.on('mouseleave', function () {
                    $btns.stop().animate({
                        height: 0
                    });
                });

                $btns.on('click', 'span', function () {
                    var index = $(this).index(), deg;

                    switch (index) {
                        case 0:
                            uploader.removeFile(file);
                            return;

                        case 1:
                            file.rotation += 90;
                            break;

                        case 2:
                            file.rotation -= 90;
                            break;
                    }

                    if (supportTransition) {
                        deg = 'rotate(' + file.rotation + 'deg)';
                        $wrap.css({
                            '-webkit-transform': deg,
                            '-mos-transform': deg,
                            '-o-transform': deg,
                            'transform': deg
                        });
                    } else {
                        $wrap.css('filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' + (~~((file.rotation / 90) % 4 + 4) % 4) + ')');
                    }

                });

                $li.appendTo($queue);
            }

            // 负责view的销毁
            function removeFile(file) {
                var $li = $('#' + file.id);

                delete percentages[file.id];
                updateTotalProgress();
                $li.off().find('.file-panel').off().end().remove();
            }

            function updateTotalProgress() {
                var loaded = 0, total = 0, spans = $progress.children(), percent;

                $.each(percentages, function (k, v) {
                    total += v[0];
                    loaded += v[0] * v[1];
                });

                percent = total ? loaded / total : 0;

                spans.eq(0).text(Math.round(percent * 100) + '%');
                spans.eq(1).css('width', Math.round(percent * 100) + '%');
                updateStatus();
            }

            function updateStatus() {
                var text = '', stats;

                if (state === 'ready') {
                    text = '选中' + fileCount + '张图片，共' + WebUploader.formatSize(fileSize) + '。';
                } else if (state === 'confirm') {
                    stats = uploader.getStats();
                    if (stats.uploadFailNum) {
                        text = '已成功上传' + stats.successNum + '张照片，' + stats.uploadFailNum + '张照片上传失败，<a class="retry" href="#">重新上传</a>失败图片或<a class="ignore" href="#">忽略</a>'
                    }

                } else {
                    stats = uploader.getStats();
                    text = '共' + fileCount + '张（' + WebUploader.formatSize(fileSize) + '），已上传' + stats.successNum + '张';

                    if (stats.uploadFailNum) {
                        text += '，失败' + stats.uploadFailNum + '张';
                    }
                }

                $info.html(text);
            }

            function setState(val) {
                var file, stats;

                if (val === state) {
                    return;
                }

                $upload.removeClass('state-' + state);
                $upload.addClass('state-' + val);
                state = val;

                switch (state) {
                    case 'pedding':
                        $placeHolder.removeClass('element-invisible');
                        $queue.hide();
                        $statusBar.addClass('element-invisible');
                        uploader.refresh();
                        break;

                    case 'ready':
                        $placeHolder.addClass('element-invisible');
                        $('#filePicker2').removeClass('element-invisible');
                        $queue.show();
                        $statusBar.removeClass('element-invisible');
                        uploader.refresh();
                        $upload.text('开始上传').removeClass('disabled');
                        break;

                    case 'uploading':
                        $('#filePicker2').addClass('element-invisible');
                        $progress.show();
                        $upload.text('暂停上传');
                        break;

                    case 'paused':
                        $progress.show();
                        $upload.text('继续上传');
                        break;

                    case 'confirm':
                        $progress.hide();
                        $upload.text('开始上传').addClass('disabled');

                        stats = uploader.getStats();
                        if (stats.successNum && !stats.uploadFailNum) {
                            setState('finish');
                            return;
                        }
                        break;
                    case 'finish':
                        stats = uploader.getStats();
                        if (stats.successNum) {

                            // WuZhiFeng

                        } else {
                            // 没有成功的图片，重设
                            state = 'done';
                            location.reload();
                        }
                        $('#filePicker2').removeClass('element-invisible');
                        $upload.text('开始上传').removeClass('disabled');
                        break;
                }

                updateStatus();
            }

            uploader.onUploadProgress = function (file, percentage) {
                var $li = $('#' + file.id), $percent = $li.find('.progress span');

                $percent.css('width', percentage * 100 + '%');
                if ($.isEmptyObject(percentages)) {
                    return false;
                }
                percentages[file.id][1] = percentage;
                updateTotalProgress();
            };

            uploader.onFileQueued = function (file) {
                fileCount++;
                fileSize += file.size;

                if (fileCount === 1) {
                    $placeHolder.addClass('element-invisible');
                    $statusBar.show();
                }

                addFile(file);
                setState('ready');
                updateTotalProgress();
            };

            uploader.onFileDequeued = function (file) {
                fileCount--;
                fileSize -= file.size;

                if (!fileCount) {
                    setState('pedding');
                }

                removeFile(file);
                updateTotalProgress();

            };

            uploader.on('all', function (type) {
                var stats;
                switch (type) {
                    case 'uploadFinished':
                        setState('confirm');
                        break;

                    case 'startUpload':
                        setState('uploading');
                        break;

                    case 'stopUpload':
                        setState('paused');
                        break;

                }

            });

            uploader.onError = function (code) {
                if (code == 'Q_TYPE_DENIED') {
                    alert("不支持该文件类型，请选择图片类型文件");
                }
                if (code == 'Q_EXCEED_NUM_LIMIT') {
                    alert("只能上传单张图片");
                }
                // alert( 'Eroor: ' + code );
            };

            $upload.on('click', function () {
                if ($(this).hasClass('disabled')) {
                    return false;
                }

                if (state === 'ready') {
                    uploader.upload();
                } else if (state === 'paused') {
                    uploader.upload();
                } else if (state === 'uploading') {
                    uploader.stop();
                }
            });

            $info.on('click', '.retry', function () {
                uploader.retry();
            });

            $info.on('click', '.ignore', function () {
                alert('todo');
            });

            $upload.addClass('state-' + state);
            updateTotalProgress();


        });
    }

    var resetUploader = function () {
        if (uploader) {
            //重新设置页面
            for (var i = 0; i < uploader.getFiles().length; i++) {
                uploader.removeFile(uploader.getFiles()[i]);
            }
            uploader.stop();
            uploader.reset();
        }
        $('.webuploader-element-invisible').val('');
    };

    $(".closed").unbind();
    $(".sure").unbind();


    $(".sure").on('click', function () {


        var attachImg = [];
        var attachimg = [];
        var attachFile = [];
        var attachfile = [];
        var flag2 = false;
        /*var status = uploader.getStats();
        console.log(status);
        if (status.queueNum) {
            $(".statusBar .info").html("还有" + status.queueNum + "张图片未上传");
            return
        }*/
        $('#image_upload_pop').toggle();
        resetUploader();

        var img = $("#picStay a");
        var file = $("#fileStay a");

        if (img.length) {
            $.each(img, function (i, e) {
                attachImg.push(
                    {
                        playHref: $(e).attr('playhref'),
                        href: $(e).attr('href'),
                        attachId: attachId
                    }
                );
            })

            $.each(img, function (i, e) {
                attachimg.push($(e).attr('href'))
            })

            var sameAttach = $('[attachid=' + attachId + '] li');
            if (sameAttach.length) {
                $.each(sameAttach, function (i, e) {
                    attachimg.push($(e).attr('href'))
                })
            }
        }

        if (file.length) {
            $.each(file, function (i, e) {
                attachFile.push(
                    {
                        playHref: $(e).attr('playhref'),
                        href: $(e).attr('href'),
                        attachId: attachId,
                        name: $(e).attr('name'),
                        type: $(e).attr('type')
                    }
                );
            })

            $.each(file, function (i, e) {
                attachfile.push($(e).attr('href'))
            })

            var sameAttach = $('[fileAttachId=' + attachId + '] li');
            if (sameAttach.length) {
                $.each(sameAttach, function (i, e) {
                    attachfile.push($(e).attr('href'))
                })
            }
        }

        if (attachImg.length) {
            if ($('[attachId]').length) {
                $.each($('[attachId]'), function (i, e) {
                    if (attachImg[0].attachId == $(e).attr('attachId')) {
                        $.each(attachImg, function (ii, ee) {
                            $(e).append('<li href=\"' + ee.href + '\">   \n' +
                                '<img class="img_00" url="' + ee.href + '" src="' + ee.playHref + '">\n' +
                                '<i class="delSingleAttach iconfont icon-minus">\n' +
                                '</i>\n' +
                                '</li>')
                        })

                        $("#picStay").html("");
                        flag2 = false;
                    }
                })

                if (flag2) {
                    $('#image_list').append("<tr><td>" + data.content[0].attachName + "</td><td class=\"minImg\"><div id=\"gallery" + data.content[0].attachId + "\" attachName=\"" + data.content[0].attachName + "\" attachId=\"" + data.content[0].attachId + "\" allid=" + data.content[0].id + "></div></td><td><i class=\"delAttach iconfont icon-shanchu\"></i></td></tr>");
                    $.each(attachImg, function (ii, ee) {
                        var gallery = $('[attachId=' + ee.attachId + ']');
                        gallery.append('<li href=\"' + ee.href + '\">   \n' +
                            '<img class="img_00" url="' + ee.href + '" src="' + ee.playHref + '">\n' +
                            '<i class="delSingleAttach iconfont icon-minus">\n' +
                            '</i>\n' +
                            '</li>')
                    })

                    //imgList(data.content[0].attachId);
                    $("#picStay").html("");
                }
            }

            else {
                $('#image_list').append("<tr><td>" + data.content[0].attachName + "</td><td class=\"minImg\"><div id=\"gallery" + data.content[0].attachId + "\" attachName=\"" + data.content[0].attachName + "\" attachId=\"" + data.content[0].attachId + "\" allid=" + data.content[0].id + "></div></td><td><i class=\"delAttach iconfont icon-shanchu\"></i></td></tr>");
                $.each(attachImg, function (ii, ee) {
                    var gallery = $('[attachId=' + ee.attachId + ']');
                    gallery.append('<li href=\"' + ee.href + '\">   \n' +
                        '<img class="img_00" url="' + ee.href + '" src="' + ee.playHref + '">\n' +
                        '<i class="delSingleAttach iconfont icon-minus">\n' +
                        '</i>\n' +
                        '</li>')
                })

                //imgList(data.content[0].attachId);
                $("#picStay").html("");
            }
            $('.processForm_winBox .winBox1').viewer('destroy').viewer();
            Constant.fn.initScroll();
            $('.cover').show();
        }

        if (attachFile.length) {
            if ($('[fileAttachId]').length) {
                $.each($('[fileAttachId]'), function (i, e) {
                    if (attachFile[0].attachId == $(e).attr('fileattachid')) {
                        $.each(attachFile, function (ii, ee) {
                            var type;
                            if (ee.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
                                type = 'static/css/images/word.png';
                            } else if (ee.type === 'application/pdf') {
                                type = 'static/css/images/pdf.png';
                            } else if (ee.type === 'application/vnd.ms-excel') {
                                type = 'static/css/images/xls.png';
                            }
                            /*if (ee.type == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
                                $(e).append("<a onclick='openmydoc(\"" + ee.href + "\")' type='activxobject(word.application)'>   \n" +
                                    '<img class="img_00" url="' + ee.href + '" src="' + type + '">\n' +
                                    '<div>' + ee.name + '</div>\n' +
                                    '<i class="delSingleFileAttach iconfont icon-minus">\n' +
                                    '</i>\n' +
                                    '</a>'
                                )
                            } else {*/
                            $(e).append('<a href=\"' + ee.href + '\" target="_blank">   \n' +
                                '<img class="img_00" url="' + ee.href + '" src="' + type + '">\n' +
                                '<div>' + ee.name + '</div>\n' +
                                '<i class="delSingleFileAttach iconfont icon-minus">\n' +
                                '</i>\n' +
                                '</a>'
                            )
                            //}
                        })

                        $("#fileStay").html("");
                        flag2 = false;
                    }
                })

                if (flag2) {
                    $('#image_list').append("<tr><td>" + data.content[0].attachName + "</td><td class=\"minImg\"><div id=\"gallery" + data.content[0].attachId + "\" attachName=\"" + data.content[0].attachName + "\" attachId=\"" + data.content[0].attachId + "\" allid=" + data.content[0].id + "></div></td><td><i class=\"delAttach iconfont icon-shanchu\"></i></td></tr>");
                    $.each(attachFile, function (ii, ee) {
                        var type;
                        if (ee.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
                            type = 'static/css/images/word.png';
                        } else if (ee.type === 'application/pdf') {
                            type = 'static/css/images/pdf.png';
                        } else if (ee.type === 'application/vnd.ms-excel') {
                            type = 'static/css/images/xls.png';
                        }
                        var gallery = $('[fileAttachId=' + ee.attachId + ']');
                        /*if (ee.type == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
                            gallery.append("<a onclick='openmydoc(\"" + ee.href + "\")' type='activxobject(word.application)'>   \n" +
                                '<img class="img_00" url="' + ee.href + '" src="' + type + '">\n' +
                                '<div>' + ee.name + '</div>\n' +
                                '<i class="delSingleFileAttach iconfont icon-minus">\n' +
                                '</i>\n' +
                                '</a>')*/
                        //}else{
                        gallery.append('<a href=\"' + ee.href + '\" target="_blank">   \n' +
                            '<img class="img_00" url="' + ee.href + '" src="' + type + '">\n' +
                            '<div>' + ee.name + '</div>\n' +
                            '<i class="delSingleFileAttach iconfont icon-minus">\n' +
                            '</i>\n' +
                            '</a>')
                        //}
                    })

                    //imgList(data.content[0].attachId);
                    $("#fileStay").html("");
                }
            }

            else {
                $('#image_list').append("<tr><td>" + data.content[0].attachName + "</td><td class=\"minImg\"><div id=\"gallery" + data.content[0].attachId + "\" attachName=\"" + data.content[0].attachName + "\" attachId=\"" + data.content[0].attachId + "\" allid=" + data.content[0].id + "></div></td><td><i class=\"delAttach iconfont icon-shanchu\"></i></td></tr>");
                $.each(attachFile, function (ii, ee) {
                    var type;
                    if (ee.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
                        type = 'static/css/images/word.png';
                    } else if (ee.type === 'application/pdf') {
                        type = 'static/css/images/pdf.png';
                    } else if (ee.type === 'application/vnd.ms-excel') {
                        type = 'static/css/images/xls.png';
                    }
                    var gallery = $('[fileAttachId=' + ee.attachId + ']');
                    gallery.append('<a href=\"' + ee.href + '\">   \n' +
                        '<img class="img_00" url="' + ee.href + '" src="' + type + '">\n' +
                        '<div>' + ee.name + '</div>\n' +
                        '<i class="delSingleFileAttach iconfont icon-minus">\n' +
                        '</i>\n' +
                        '</a>')
                })

                //imgList(data.content[0].attachId);
                $("#fileStay").html("");
            }
            //$('.processForm_winBox .winBox1').viewer('destroy').viewer();
            //Constant.fn.initScroll();
            Constant.fn.initFileScroll();
            $('.fileCover').show();
        }
        //删除单张图片
        $('.delSingleAttach').unbind().on('click', function (e) {
            e.stopPropagation();
            e.preventDefault();
            $(this).parents('li').remove();

            Constant.fn.initScroll();
        })

        //删除单个文件
        $('.delSingleFileAttach').unbind().on('click', function (e) {
            e.stopPropagation();
            e.preventDefault();
            $(this).parents('a').remove();

            Constant.fn.initFileScroll();
        })
    })

    $(".closed").on('click', function () {
        //uploader.stop();
        //uploader.reset();
        resetUploader();
        //uploader.destroy();
        $('#image_upload_pop').toggle();
        $("#picStay").html("");
    })


    //判断是否显示左右箭头

    console.log(1);


    OSS_IMAGE_INIT(order_id, node_id);
})

/**
 * 从ueditor.all.js里面拷贝的拖拽方法
 */
var _onTitlebarMouseDown = function (event, el) {
    var uiUtils = baidu.editor.ui.uiUtils;
    var domUtils = baidu.editor.dom.domUtils;
    var rect;
    var me = this;
    var dialogId = el.getAttribute('id');//'image_upload_pop';

    var safeSetOffset = function (offset) {
        // var me = this;
        var el = getDom();
        var vpRect = uiUtils.getViewportRect();
        var rect = uiUtils.getClientRect(el);
        var left = offset.left;
        if (left + rect.width > vpRect.right) {
            left = vpRect.right - rect.width;
        }
        var top = offset.top;
        if (top + rect.height > vpRect.bottom) {
            top = vpRect.bottom - rect.height;
        }
        el.style.left = Math.max(left, 0) + 'px';
        el.style.top = Math.max(top, 0) + 'px';
    }
    var getDom = function (name) {
        if (!name) {
            return document.getElementById(dialogId);
        } else {
            return document.getElementById(dialogId + '_' + name);
        }
    };

    uiUtils.startDrag(event, {
        ondragstart: function () {
            rect = uiUtils.getClientRect(getDom());
            // me.getDom('contmask').style.visibility = 'visible';
            // me.dragMask.show(me.getDom().style.zIndex - 1);
        },
        ondragmove: function (x, y) {
            var left = rect.left + x;
            var top = rect.top + y;
            safeSetOffset({
                left: left,
                top: top
            });
        },
        ondragstop: function () {
            // me.getDom('contmask').style.visibility = 'hidden';
            // domUtils.removeClasses(me.getDom(), ['edui-state-centered']);
            // me.dragMask.hide();
        }
    });

};

var centerPosition = function (el) {
    var uiUtils = baidu.editor.ui.uiUtils;
    var vpRect = uiUtils.getViewportRect();
    var rect = uiUtils.getClientRect(el);
    var left = vpRect.width / 2 - rect.width / 2;
    var top = vpRect.height / 2 - rect.height / 2;

    el.style.left = Math.max(left, 0) + 'px';
    el.style.top = Math.max(top, 0) + 'px';
};
